const cheerio = require('cheerio')
const { request, request2 } = require('./request')
const utils2 = require('./utils')
const tag = '粉丝' // 粉丝

let requestInterval = 350
let tbs_exp
// 删除多个
async function deleteMultiple(config, ws, webconfig) {

  let { start, end, interval } = config
  requestInterval = interval || 350
  if (!start || !end) {
    if (start) {
      end = start
    } else if (end) {
      start = end
    } else {
      sendMessage(`${tag}: 请设置开始和结束页 `, ws)
      return false
    }
  } else if (start > end) {
    start = end
  }

  const list = await getMultiplePage(start, end, ws, webconfig)
  const len = list.length
  if (len === 0) {
    sendMessage(`${tag}: 完成`, ws)
    return false
  }

  for (let index = 0; index < list.length; index++) {
    sendMessage(`${tag}: ${list[index].un} 用户昵称:${list[index].name}`, ws)
    const status = await deleteOne(list[index], ws, webconfig)
    if (status) {
      sendMessage(`${tag}: >>> 删除限制 <<< , 请明天再尝试`, ws)
      return false
    }
    if(webconfig && webconfig.isRunning === "NO" ){
      return false
    }
  }
  sendMessage(`${tag}: 完成`, ws)
}

// 删除一个
async function deleteOne(params, ws, webconfig) {
  const fd = new URLSearchParams()
  Object.keys(params).forEach(key => {
    // fd.append(key, params[key])
    fd.append('ie', 'utf-8')
    fd.append('cmd', 'add_black_list')
    fd.append('portrait', params.portrait)
    if (webconfig) {
      fd.append('tbs', webconfig.tbs)
    } else {
      fd.append('tbs', tbs_exp)
    }
  })

  const url = 'https://tieba.baidu.com/i/commit'
  const response = await sendRequest(url, fd, webconfig)
  const data = await response.json()

  return new Promise(resolve => {
    setTimeout(() => {
      let message
      if (data.is_done === true) {
        message = `${tag}: 操作完成` + JSON.stringify(data)
        resolve(false)
      } else {
        message = `${tag}: 操作错误:` + JSON.stringify(data)
        resolve(true)
      }
      sendMessage(message, ws)
    }, requestInterval)
  })
}

// 获取多页
async function getMultiplePage(start, end, ws, webconfig) {
  sendMessage(`${tag}: 获取,页面:${start}->${end}`, ws)
  const data = []
  for (let page = start; page <= end; page++) {
    let list = await getOnePage(page, ws, webconfig)
    data.push(...list)
  }
  sendMessage(`${tag}: 获得总数: ${data.length}`, ws)
  return data
}

// 获取一页
async function getOnePage(page, ws, webconfig) {
  const url = `https://tieba.baidu.com/i/i/fans?pn=${page}`
  const response = await sendRequest(url, null, webconfig)
  const data = await response.text()
  const $ = cheerio.load(data)

  if (!tbs_exp) {
    tbs_exp = await utils2.getTBS16(data);
  }

  const list = $('div.user').map((index, el) => {
    return {
      cmd: 'add_black_list',
      name: $(el).find('span.name').text(),
      portrait: $(el).find('input.btn_follow').attr('portrait'),
      un: $(el).find('input.btn_follow').attr('name')
    }
  });

  return new Promise(resolve => {
    setTimeout(() => {
      sendMessage(`${tag}: 获得页面:${page}, 数量:${list.length}`, ws)
      resolve(list)
    }, requestInterval)
  })
}
// 输出消息
async function sendMessage(message2, ws) {
  if (typeof ws !== "undefined" && ws !== null) {
    ws.send(JSON.stringify({ status: 'message', message: message2 }));
  } else {
    // console.log(message2)
  }
  console.log(message2)
}

// 发送请求
async function sendRequest(url, fb, webconfig) {
  if (typeof webconfig !== "undefined" && webconfig !== null) {
    return await request2(url, webconfig.cookie, fb)
  } else {
    return await request(url, fb)
  }
}


module.exports.deleteFans = deleteMultiple